<template>
  <el-dialog
    :title="title"
    :visible.sync="isVisible"
    :width="width"
    :before-close="handleClose"
    :lock-scroll="true"
    :close-on-click-modal="false"
    custom-class="pub_dialog"
    @open="getData"
  >
    <VForm
      ref="vformComponents"
      :form="formData.form"
      :options="formData.options"
      :rules="formData.rules"
      :labelWidth="formData.labelWidth"
      :rowspan="rowspan"
      @changeAddress="changeAddress"
      @toLoadMethods="toLoadMethods"
    ></VForm>

    <span slot="footer" class="dialog-footer">
     <el-button @click="cancel">{{openType!='detail' ? '取 消':'返 回'}}</el-button>
     <el-button type="primary" @click="sure" v-if="openType!='detail'">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import { riskRescueTeamDetail,
    riskRescueTeamUpdate,
    riskRescueTeamAdd } from '@/api/risk/rescueTeam'
  import VForm from "@/components/VForm/index";
  export default {
    components: {
      VForm,
    },
    props: {
      width: {
        type: String,
        default: "70%",
      },
      title: {
        type: String,
        default: "详情",
      },
      id:{},
      openType:{
        type:String,
        default:"add"
      },
      dialogVisible: {
        type: Boolean,
        default: false
      }
    },
    watch: {
      'width': {
        handler(newVal, oldVal) {
          console.log('newVal===',newVal, oldVal)
          let w = this.width.split('%')[0]
          if(w>=60){
            this.rowspan = 2
          }else{
            this.rowspan = 1
          }
        },
        deep: true,
        immediate: true
      },
      'teamLevelOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='teamLevel'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'typeOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='type'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'secretLevelOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='secretLevel'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'dataSourceList': {
        handler(newVal, oldVal) {
          this.formData.options.forEach(t => {
            if (t.key == 'dataSourceId') {
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'openType':{
        handler(newVal, oldVal) {
          // 判断是否详情，添加不可编辑标识
          this.formData.options.forEach(t=>{
            t.disabled = newVal=='detail' ? true : false
          })
        },
        deep: true,
        immediate: true
      }
    },
    computed: {
      isVisible: {
        get() {
          return this.dialogVisible
        },
        set() {
          this.close()
        }
      }
    },
    data() {
      return {
        rowspan:1,
        dict:{},
        formData: {
          form: {
            name:"",
            type:"",
            personNum:"",
            setUpTime:"",
            teamLevel:"",
            qualificationsLevel:"",
            teamNature:"",
            secretLevel:"",
            affiliatedUnit:"",
            director:"",
            directorPhone:"",
            dutyPhone:"",
            faxNum:"",
            communication:"",
            preparationTime:"",
            experience:"",
            duty:"",
            equipDescribe:"",
            file:[],
            remark:"",
            areaCode:"",
            mapData:null,
            dataSource:"",
            dataSourceId:""
          },
          options: [
            {
              title: "救援队伍名称",
              key: "name",
              type: "text",
            },
            {
              title: "救援队伍类型",
              key: "type",
              type: "select",
              multiple:false,
              option: {
                data: this.typeOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "value", // 指定value对应data的字段
                },
              },
            },
            {
              title: "人数",
              key: "personNum",
              type: "text",
            },
            {
              title: "成立时间",
              key: "setUpTime",
              type: "date",
            },
            {
              title: "级别",
              key: "teamLevel",
              type: "select",
              multiple:false,
              option: {
                data: this.teamLevelOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "value", // 指定value对应data的字段
                },
              },
            },
            {
              title: "资质等级",
              key: "qualificationsLevel",
              type: "text",
            },
            {
              title: "性质",
              key: "teamNature",
              type: "text",
            },
            {
              title: "机密等级",
              key: "secretLevel",
              type: "select",
              multiple:false,
              option: {
                data: this.secretLevelOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "value", // 指定value对应data的字段
                },
              },
            },
            {
              title: "隶属单位",
              key: "affiliatedUnit",
              type: "text",
            },
            {
              title: "负责人姓名",
              key: "director",
              type: "text",
            },
            {
              title: "负责人电话",
              key: "directorPhone",
              type: "text",
            },
            {
              title: "值班电话",
              key: "dutyPhone",
              type: "text",
            },
            {
              title: "传真号码",
              key: "faxNum",
              type: "text",
            },
            {
              title: "应急通信方式",
              key: "communication",
              type: "text",
            },
            {
              title: "应急准备时间(分钟)",
              key: "preparationTime",
              type: "text",
            },
            {
              title: "应急救援经历",
              key: "experience",
              type: "text",
            },
            {
              title: "主要职责与专长",
              key: "duty",
              type: "text",
            },
            {
              title: "装备描述",
              key: "equipDescribe",
              type: "text",
            },
            {
              title: "行政区划",
              key: "areaCode",
              type: "gdAreaSelect",
            },
            // {
            //   title: "数据来源单位",
            //   key: "dataSourceId",
            //   type: "select",
            //   event: "changeDataSource",
            //   multiple:false,
            //   option: {
            //     data: this.dataSourceList,
            //     props: {
            //       key: "id", // 指定key对应data的字段
            //       label: "name", // 指定label对应data的字段
            //       value: "id", // 指定value对应data的字段
            //     },
            //   },
            // },
            {
              title: "数据来源单位",
              key: "dataSource",
              type: "text",
            },
            {
              title: "备注",
              key: "remark",
              type: "text",
            },
            {
              title: "附件",
              key: "file",
              type: "file",
              fileType:"file",
              listType:"text",
              uploadTextTip:""
            },
            {
              title:'地点选择',
              type:'mapPosition',
              key:'mapData',
            },
          ],
          rules: {
            name :[
              { required: true, message: '请输入', trigger: 'blur' },
              {max:64, message: '长度最大为64个字符', trigger: 'blur'}
            ],
            type :[
            ],
            personNum :[
            ],
            setUpTime :[
            ],
            teamLevel :[
            ],
            qualificationsLevel :[
              {max:64, message: '长度最大为64个字符', trigger: 'blur'}
            ],
            teamNature :[
              {max:64, message: '长度最大为64个字符', trigger: 'blur'}
            ],
            secretLevel :[
            ],
            affiliatedUnit :[
              {max:64, message: '长度最大为64个字符', trigger: 'blur'}
            ],
            director :[
              {max:36, message: '长度最大为36个字符', trigger: 'blur'}
            ],
            directorPhone :[
              {max:36, message: '长度最大为36个字符', trigger: 'blur'}
            ],
            dutyPhone :[
              {max:36, message: '长度最大为36个字符', trigger: 'blur'}
            ],
            faxNum :[
              {max:64, message: '长度最大为64个字符', trigger: 'blur'}
            ],
            communication :[
              {max:36, message: '长度最大为36个字符', trigger: 'blur'}
            ],
            preparationTime :[
            ],
            experience :[
              {max:256, message: '长度最大为256个字符', trigger: 'blur'}
            ],
            duty :[
              {max:256, message: '长度最大为256个字符', trigger: 'blur'}
            ],
            equipDescribe :[
              {max:256, message: '长度最大为256个字符', trigger: 'blur'}
            ],
            file :[
            ],
            remark :[
              {max:256, message: '长度最大为256个字符', trigger: 'blur'}
            ],
            mapData :[
              { required: true, message: '请设置', trigger: 'change' },
            ],
          },
          labelWidth: "140px",
        },
        // 字典
        typeOptions:[],
        teamLevelOptions:[],
        secretLevelOptions:[],
        dataSourceList:[]
      };
    },
    methods: {
      toLoadMethods(methods) {
        this[methods]()
      },
      changeDataSource(){
        let item = this.dataSourceList.find(t=> t.id == this.formData.form.dataSourceId)
        if(undefined!=item){
          this.formData.form.dataSource = item.name
        }
      },
      initData(){
          this.formData.form.name="",
          this.formData.form.type="",
          this.formData.form.personNum="",
          this.formData.form.setUpTime="",
          this.formData.form.teamLevel="",
          this.formData.form.qualificationsLevel="",
          this.formData.form.teamNature="",
          this.formData.form.secretLevel="",
          this.formData.form.affiliatedUnit="",
          this.formData.form.director="",
          this.formData.form.directorPhone="",
          this.formData.form.dutyPhone="",
          this.formData.form.faxNum="",
          this.formData.form.communication="",
          this.formData.form.preparationTime="",
          this.formData.form.experience="",
          this.formData.form.duty="",
          this.formData.form.equipDescribe="",
          this.formData.form.file=[],
          this.formData.form.remark="",
          this.formData.form.areaCode="",
          this.formData.form.mapData=null
          this.formData.form.dataSource = ''
          this.formData.form.dataSourceId = ''
      },
      getCountySubIndex(cityCode){
        // 中山、东莞截取10位
        let filterList = ['442000000000','441900000000']
        if(filterList.findIndex(t=>t==cityCode)>-1){
          return 10;
        }
        return 6;
      },
      positionSubmitFormat(){
        let mapData = this.formData.form.mapData
        if(mapData){
          this.formData.form.lon = mapData.gpsX
          this.formData.form.lat = mapData.gpsY
          this.formData.form.address = mapData.address
          this.formData.form.areaCode = mapData.towncode
          if(mapData.towncode){
            this.formData.form.provinceCode = mapData.towncode.substr(0,2).padEnd(12,'0')
            this.formData.form.cityCode = mapData.towncode.substr(0,4).padEnd(12,'0')
            let subIndex = this.getCountySubIndex(this.formData.form.cityCode)
            this.formData.form.countyCode = mapData.towncode.substr(0,subIndex).padEnd(12,'0')
          }
          return true
        }
        return false
      },
      positionLoadFormat(){
        let form = this.formData.form
        let mapData = {}
        if(form.address){
          mapData.address = form.address
        }
        if(form.lon) {
          mapData.gpsX = parseFloat(form.lon)
        }
        if(form.lat) {
          mapData.gpsY = parseFloat(form.lat)
        }
        if(form.areaCode && form.provinceCode && form.cityCode && form.countyCode) {
          mapData.towncode = form.areaCode
          this.formData.form.areaCode = [form.provinceCode, form.cityCode, form.countyCode]
          this.formData.form.mapData = mapData
          return
        }
        // 空置设置默认经纬度
        this.formData.form.mapData = {gpsX: 113.280637, gpsY: 23.125178}
        console.log("mpap",mapData)
      },
      submitFormat(){
        this.formData.form.file = JSON.stringify(this.formData.form.file)
      },
      loadFormat(){
        this.formData.form.file  = this.formData.form.file ? JSON.parse(this.formData.form.file) : []
      },
      getCheckBoxData(value,option,type){
        if(type=="submit"){
          if(value.length==0){
            return null
          }
          let temp = [];
          value.forEach(t=>{
            let item = option.find(x=> x.label == t)
            if(item!=undefined){
              temp.push(item.value)
            }
          })
          return temp.join(",")
        }else {
          if(!value){
            return []
          }else {
            let data = value.split(",")
            let temp = []
            data.forEach(t=>{
              let item = option.find(x=> x.value == t)
              if(item!=undefined){
                temp.push(item.label)
              }
            })
            return temp
          }
        }
      },
      sure(){
        console.log('sure===',this.formData.form)
        this.$refs.vformComponents.$refs.form.validate().then(res=>{
          let haveAddress = this.positionSubmitFormat()
          if(!haveAddress){
            this.$message.warning("请设置地址信息")
            return
          }
          this.submitFormat()
          if(this.openType == "add"){
            this.add()
          }else{
            this.update()
          }
        })
      },
      add(){
        this.formData.form.id = null
        riskRescueTeamAdd(this.formData.form).then(res=>{
          if(res.code==200){
            this.$message({
              message: this.$t('tips.createSuccess'),
              type: 'success'
            })
            this.closeSuccess()
          }else{
            this.$message({
              message: this.$t('tips.systemException'),
              type: 'error'
            })
          }
        })
      },
      update(){
        riskRescueTeamUpdate(this.formData.form).then(res=>{
          if(res.code==200){
            this.$message({
              message: this.$t('tips.updateSuccess'),
              type: 'success'
            })
            this.closeSuccess()
          }else{
            this.$message({
              message: this.$t('tips.systemException'),
              type: 'error'
            })
          }
        })
      },
      cancel(){
        this.close()
      },
      handleClose(done) {
        done()
        this.close()
      },
      closeSuccess(){
        this.initData()
        this.$refs.vformComponents.$refs.form.resetFields();
        this.$emit('success')
      },
      close(){
        this.initData()
        this.$refs.vformComponents.$refs.form.resetFields();
        this.$emit('close')
      },
      changeAddress(data){
        // console.log(data)
        this.formData.form.mapData = data
        this.formData.form.areaCode = data.areaCode
      },
      getDataSourceData(){
        this.dataSourceList = [{id:"123",name:"部门1"},{id:"456",name:"部门2"}]
      },
      getData(){
          this.getDataSourceData()
          this.typeOptions=[],
          this.teamLevelOptions=[],
          this.secretLevelOptions=[]
          this.$commonJs.filterDataDict("riskRescueTeamType",this.typeOptions)
          this.$commonJs.filterDataDict("riskTeamLevel",this.teamLevelOptions)
          this.$commonJs.filterDataDict("riskTeamSecretLevel",this.secretLevelOptions)
        if(this.openType!="add"){
          riskRescueTeamDetail(this.id).then(res=>{
            if(res.code==200){
              this.formData.form = res.data
              this.loadFormat()
              this.positionLoadFormat()
            }else{
              this.$message({
                message: this.$t('tips.systemException'),
                type: 'error'
              })
            }
          })
        }
      }
    },
  };
</script>

<style lang="scss" scoped>

</style>
